package ranab.io;

import java.io.*;

/**
 * This class counts the lines of all the files in a
 * directory and subdirectory. It also counts the number
 * of files.
 */
public 
class CounterFileAction implements FileAction {

    private long mlLineCount = 0;
    private int miFileCount = 0;

    /**
     * Does nothing
     * @see ranab.io.FileAction#startAction()
     */
    public void startAction() {
    }

    /**
     * Count the number of lines.
     * @see ranab.io.FileAction#actionPerformed(File)
     */
    public void actionPerformed(File fl) {
       try {
            if(!fl.isFile()) {
                return;
            }
        
            ++miFileCount;
            FileReader frd = new FileReader(fl);
            BufferedReader br = new BufferedReader(frd);
            
            String line = null;
            while( (line = br.readLine()) != null ) {
                ++mlLineCount;
            }
            
            br.close();
       }
       catch(Exception ex) {
          ex.printStackTrace();
       }
    }

    /**
     * Does nothing
     * @see ranab.io.FileAction#endAction()
     */
    public void endAction() {
    }
    
    /**
     * Get line count
     */
    public long getLineCount() {
        return mlLineCount;
    }
    
    /**
     * Get file count
     */
    public int getFileCount() {
        return miFileCount;
    }
    
    /**
     * Main method to start line counting
     */
    public static void main(String args[]) {
        
        // argument check
        if(args.length != 1) {
            System.err.println("Usage : java ranab.io.LineCounterFileAction <directory>");
            System.exit(1);
        }
    
        CounterFileAction action = new CounterFileAction();
        FileNavigator navigator = new FileNavigator(new File(args[0]), action);
        navigator.run();
        System.out.println("Line count = " + action.getLineCount());
        System.out.println("File count = " + action.getFileCount());
    }
}
